//
//  TrainTicketScreeningView.swift
//  AirTravel
//
//  Created by apple on 2021/8/12.
//

import UIKit
import FWPopupView

protocol TicketScreeningDelegate:NSObjectProtocol {
    func ticketScreeningClick(dic:Dictionary<String,Any>)
}

class TrainTicketScreeningView: FWPopupView {
    var contentView:UIView!
    weak var delegate: TicketScreeningDelegate?
    
    @IBOutlet weak var collView: UICollectionView!
    let identifyPR = "PriceReusableView"
    let identifyPS = "PriceStarColl"
    var stationNameList : Array<Any>?
    let trainArray = ["全部","高铁G/C","动车D","普通Z/T/K","其他Y/L"]
    let timeArray = ["全部","00:00-06:00","06:00-12:00","12:00-18:00","18:00:-24:00"]
    var trainNumber = -1
    var timeNumber = -1
    var stationName = [String]()
    
    
    // 初始化时将xib中的view添加进来
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView = loadViewFromNib()
        contentView.frame = self.bounds
        contentView.backgroundColor = UIColor.white
        self.insertSubview(contentView, at: 0)
        
        self.collView.dataSource = self
        self.collView.delegate = self
        let layout1 = UICollectionViewFlowLayout.init()
        layout1.scrollDirection = .vertical
        
        layout1.itemSize = .init(width: (SCREEN_WIDTH - 30 - 16) / 3, height: 40)
        layout1.minimumInteritemSpacing = 8
        layout1.sectionInset = UIEdgeInsets.init(top: 6, left: 15, bottom: 6, right: 15)
        self.collView.collectionViewLayout = layout1
        self.collView.register(UINib.init(nibName: "PriceReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: identifyPR)
        self.collView.register(UINib.init(nibName: "PriceStarColl", bundle: nil), forCellWithReuseIdentifier: identifyPS)
        
    }
    
    // 初始化时将xib中的view添加进来
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // 加载xib
    func loadViewFromNib() -> UIView {
        let className = type(of: self)
        let bundle = Bundle(for: className)
        let name = NSStringFromClass(className).components(separatedBy: ".").last
        let nib = UINib(nibName: name!, bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        view.backgroundColor = UIColor.clear
        return view
    }
    
    func setUpdata(stationNameList:Array<Any>) {
        self.stationNameList = stationNameList
        if let array = self.stationNameList {
            for _ in array {
                self.stationName.append("")
            }
        }
        
    }
    
    @IBAction func backBtn(_ sender: UIButton) {
        self.hide()
        self.hideKeyboard()
    }
    
    @IBAction func submit(_ sender: Any) {
        if trainNumber == -1 {
            trainNumber = 0
        }
        if timeNumber == -1 {
            timeNumber = 0
        }
        var stationNames = [String]()
        
        for item in self.stationName {
            if item.isEmpty == false {
                stationNames.append(item)
            }
        }
        var stationNameStr = ""
        if stationNames.isEmpty == false {
            stationNameStr = stationNames.joined(separator: ",")
        }
        
        self.delegate?.ticketScreeningClick(dic: ["trainType":self.trainNumber,"timeType":self.timeNumber,"stationName":stationNameStr])
        self.hide()
        self.hideKeyboard()
    }
}

extension TrainTicketScreeningView:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return 3
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch section {
        case 0:
            return self.trainArray.count
        case 1:
            return self.timeArray.count
        default:
            return self.stationNameList?.count ?? 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifyPS, for: indexPath) as! PriceStarColl
        switch indexPath.section {
        case 0:
            cell.contentLab.text = self.trainArray[indexPath.row]
            if self.trainNumber == indexPath.row {
                cell.backView.backgroundColor = Blue_COLOR
                cell.contentLab.textColor = UIColor.white
            }else{
                cell.backView.backgroundColor = UIColor.init(hexString: "#f5f3f2")
                cell.contentLab.textColor = UIColor.black
            }
        case 1:
            cell.contentLab.text = self.timeArray[indexPath.row]
            if self.timeNumber == indexPath.row {
                cell.backView.backgroundColor = Blue_COLOR
                cell.contentLab.textColor = UIColor.white
            }else{
                cell.backView.backgroundColor = UIColor.init(hexString: "#f5f3f2")
                cell.contentLab.textColor = UIColor.black
            }
        default:
            if let array = self.stationNameList {
                cell.contentLab.text = "\(array[indexPath.row])"
            }
            let str = self.stationName[indexPath.row]
            if str.isEmpty {
                cell.backView.backgroundColor = UIColor.init(hexString: "#f5f3f2")
                cell.contentLab.textColor = UIColor.black
            }else{
                cell.backView.backgroundColor = Blue_COLOR
                cell.contentLab.textColor = UIColor.white
            }
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        //1.取出section的headerView
        let headerView : PriceReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifyPR, for: indexPath) as! PriceReusableView
        switch indexPath.section {
        case 0:
            headerView.titleLab.text = "车型选择"
        case 1:
            headerView.titleLab.text = "出发时间"
        default:
            headerView.titleLab.text = "车站名称"
        }
        headerView.priceLab.isHidden = true
        return headerView
    }
    
    //header高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: SCREEN_WIDTH, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        switch indexPath.section {
        case 0:
            self.trainNumber = indexPath.row
        case 1:
            self.timeNumber = indexPath.row
        default:
            if let array = self.stationNameList {
                let str = self.stationName[indexPath.row]
                if str.isEmpty {
                    self.stationName[indexPath.row] = "\(array[indexPath.row])"
                }else{
                    self.stationName[indexPath.row] = ""
                }
            }
        }
        self.collView.reloadData()
    }
}
